<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>基于ai的电商数据采集分析系统</h2>
      </div>
      <el-form 
        ref="loginFormRef" 
        :model="loginForm" 
        :rules="loginRules" 
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input 
            v-model="loginForm.username"
            placeholder="用户名"
            prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password"
            placeholder="密码"
            prefix-icon="Lock"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="loading" 
            class="login-button"
            @click="handleLogin"
          >登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import request from '@/utils/request'
import store from '@/store'
import { sanitizeObjectKeys } from '@/utils'

const router = useRouter()
const route = useRoute()
const loading = ref(false)
const loginFormRef = ref(null)

const loginForm = reactive({
  username: 'admin',
  password: 'admin123'
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    // 确保表单验证通过
    const valid = await loginFormRef.value.validate()
    if (!valid) {
      return
    }
    
    loading.value = true
    
    console.log('登录表单数据:', loginForm)
    
    // 使用工具函数确保对象不包含数字键
    const credentials = sanitizeObjectKeys({
      username: loginForm.username,
      password: loginForm.password
    })
    
    // 使用Vuex store的login action
    await store.dispatch('login', credentials)
    
    ElMessage.success('登录成功')
    
    // 获取重定向路径
    const redirect = route.query.redirect || '/'
    router.push(redirect)
  } catch (error) {
    console.error('登录失败:', error)
    // 确保错误消息是字符串
    const errorMessage = error && typeof error.message === 'string' ? error.message : '登录失败'
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-box {
  width: 400px;
  padding: 30px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-form {
  margin-top: 20px;
}

.login-button {
  width: 100%;
}
</style> 